﻿using System.Threading.Tasks;
using System.Linq;
using ECommon.Components;
using ECommon.IO;
using ENode.Infrastructure;
using Domain.Posts;
using Infrastructure;

namespace Denormalizers.Ef
{
    [Component]
    public class PostDenormalizer : AbstractDenormalizer,
        IMessageHandler<PostCreatedEvent>,
        IMessageHandler<PostUpdatedEvent>,
        IMessageHandler<PostReplyStatisticInfoChangedEvent>
    {
        public Task<AsyncTaskResult> HandleAsync(PostCreatedEvent evnt)
        {
            using (Repository.EntityFramework.Forums.DataContext db = new Repository.EntityFramework.Forums.DataContext())
            {
                db.Post.Add(new Repository.EntityFramework.Forums.Post
                {
                    Id = evnt.AggregateRootId,
                    Subject = evnt.Subject,
                    Body = evnt.Body,
                    SectionId = evnt.SectionId,
                    AuthorId = evnt.AuthorId,
                    CreatedOn = evnt.Timestamp,
                    UpdatedOn = evnt.Timestamp,
                    LastUpdateTime = evnt.Timestamp,
                    ReplyCount = 0,
                    Version = evnt.Version
                });
                db.Commit();
            }
            return Task.FromResult(AsyncTaskResult.Success);
        }
        public Task<AsyncTaskResult> HandleAsync(PostUpdatedEvent evnt)
        {
            using (Repository.EntityFramework.Forums.DataContext db = new Repository.EntityFramework.Forums.DataContext())
            {
                var m = db.Post.Where(x => x.Id == evnt.AggregateRootId && x.Version == evnt.Version - 1).SingleOrDefault();

                m.Subject = evnt.Subject;
                m.Body = evnt.Body;
                m.UpdatedOn = evnt.Timestamp;
                m.Version = evnt.Version;

                db.Commit();
            }
            return Task.FromResult(AsyncTaskResult.Success);
        }
        public Task<AsyncTaskResult> HandleAsync(PostReplyStatisticInfoChangedEvent evnt)
        {
            using (Repository.EntityFramework.Forums.DataContext db = new Repository.EntityFramework.Forums.DataContext())
            {
                var m = db.Post.Where(x => x.Id == evnt.AggregateRootId && x.Version == evnt.Version - 1).SingleOrDefault();

                m.MostRecentReplyId = evnt.StatisticInfo.LastReplyId;
                m.MostRecentReplierId = evnt.StatisticInfo.LastReplyAuthorId;
                m.LastUpdateTime = evnt.StatisticInfo.LastReplyTime;
                m.ReplyCount = evnt.StatisticInfo.ReplyCount;
                m.Version = evnt.Version;

                db.Commit();
            }
            return Task.FromResult(AsyncTaskResult.Success);
        }
    }
}
